//
//  ST_PeculiarityDetailShowTraitController.swift
//  btvideo
//
//  Created by mac on 2020/3/19.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import SwiftyJSON
import MJRefresh
//import ST_CHTCollectionViewWaterfallLayout

//特质详情 瀑布流 展示特质-Controller
class ST_PeculiarityDetailShowTraitController: UIViewController {
    
    
    convenience init(peculiarity_id:Int) {
        self.init(nibName:nil, bundle:nil)
        
        let m = ST_PeculiarityModel()
        m.id = peculiarity_id
        self.parent_peculiarity = m
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white

        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(view)
            make.height.equalTo(statusBarHeight+44)
        }
        view.addSubview(left_nav_btn)
        own_navigation_bar.addSubview(title_nav_btn)
        view.addSubview(right_nav_btn)
        
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(8)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        right_nav_btn.snp.makeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-14)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        right_nav_btn.isHidden = true
        
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }
        
        title_nav_btn.setTitleForAllStates(self.parent_peculiarity.name)

         
        
        view.insertSubview(collectionView, belowSubview: own_navigation_bar)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        request_data()
        
        view.addSubview(filter_btn)
        filter_btn.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize.init(width: 125, height: 50))
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-20-49)
            make.centerX.equalToSuperview()
        }
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(like_ignore_hanlde(noti:)), name: Notification.Name.ignore_somebody, object: nil)
      
        NotificationCenter.default.addObserver(self, selector: #selector(thumb_up_noti_handle(noti:)), name: Notification.Name.thumbUp, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(like_ignore_hanlde(noti:)), name: Notification.Name.ban_somebody, object: nil)
    }
    
    
    @objc fileprivate func thumb_up_noti_handle(noti:Notification){
        
        
//        不用 刷新 当前页
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController,vc != self else{
            return
        }
        
        guard let id = info["id"] as? String,let isThumbUp = info["isThumbUp"] as? Bool else{
            return
        }
        
        guard let idx = data_array.firstIndex(where: {$0.group_id.string == id}) else{
            return
        }
            
        let index = Int(idx.uInt)
        
        data_array[safe: index]?.isThumbUp = isThumbUp
        
        if isThumbUp{
            data_array[safe: index]?.thumbUpCount += 1
        }else{
            data_array[safe: index]?.thumbUpCount -= 1
        }
        
        self.collectionView.performBatchUpdates({
            
            self.collectionView.reloadItems(at: [IndexPath.init(row: index, section: 0)])
            
        }) { (f) in
            
        }
            
    }
    
    
    deinit {
//        print("特质页 开始 释放")
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func like_ignore_hanlde(noti:Notification){
            
    //         ["accid": self.accid,"likeOption":true]
        let json = JSON.init(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        let item = self.data_array.removeFirst(where: {$0.accid == accid})
            
        if item != nil{
            
            self.pause_video()
            
            self.collectionView.reloadData()
        }
    }

    
//    MARK: SetUp Data
    var parent_peculiarity = ST_PeculiarityModel()
    
    fileprivate var currentPage = 0
    
    fileprivate var searchParam = [String:Any]()
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        var param = ["page":currentPage,"feature_id":parent_peculiarity.id] as [String:Any]
        
        
        if searchParam.count > 1{
            param += searchParam
        }
        
        
        print("特质搜索参数:",param)
        
        JVrequest(PH.peculiarityDetailUserContentApi,parameters:param, success: { (json) in
            
            print("特质和人的数据：",json["data"])
            
            let data = json["data"]
            
            
            
            if let pec = ST_PeculiarityModel.deserialize(from: data["feature_detail"].dictionaryObject) {
                self.parent_peculiarity = pec
                
                self.right_nav_btn.isHidden = false
                
            }
            
            
            self.parent_peculiarity.authJson = data["auth"]
             
            let aArray = data["list"].arrayValue.map { (itemJson) -> ST_TraitOfOperatCellModel in
                let m = ST_TraitOfOperatCellModel.init(json: itemJson)
                m.create_view_model_set(maxContentHeight: ST_ShowTraitCell.two_line_max_height)
                return m
            }
//            print("七个00000----00")
//            let aArray = ST_TraitOfOperatCellModel.describe(json_array: list)
            
            if self.currentPage == 1{
                self.data_array = aArray
            }else{
                self.data_array += aArray
            }
                
            self.collectionView.reloadData {
                guard let willPlayIdx = self.determined_will_play_index_path() else { return  }
                self.play(indexPath: willPlayIdx)
            }
                
            
            self.load_more_option_style(tableView: self.collectionView, count: aArray.count, pageSize: 20) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                    self?.request_data()
                })
            }
      
            
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
    }
    
    
    
    //    MARK:- Player View
  
    fileprivate lazy var playerView:ST_PairsShareParticularView = {
        let control = ST_PairsShareParticularView()
        control.isUserInteractionEnabled = false
        control.cornerRadius = 20
        return control
    }()
    
//    MARK:- properties

    fileprivate lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("特质_icon_返回"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
//        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var right_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(ST_ImageUtils.imageName("个人中心_icon_更多操作B"), for: UIControl.State.normal)
        
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        //        control.cornerRadius = 18
//        control.backgroundColor = .random
//        control.setTitleForAllStates("帮助")
//        control.setTitleColorForAllStates(Color.init(hexString: "#333333")!)
//        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        
        
        
        control.addTarget(self, action: #selector(right_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(Color.init(hexString: "#333333")!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium)
        
        control.addTarget(self, action: #selector(title_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
       
    
    
    fileprivate lazy var transition = ST_PairsTransition()
    
    fileprivate lazy var layout:ST_CHTCollectionViewWaterfallLayout = {
       let controlLayout = ST_CHTCollectionViewWaterfallLayout()
        controlLayout.minimumColumnSpacing = 15
        controlLayout.minimumInteritemSpacing = 10
        controlLayout.sectionInset = UIEdgeInsets.init(top: 0, left: 10, bottom: BTSafeAreaBottom, right: 10)
        return controlLayout
    }()
    
    fileprivate let sectionheader_height = 175*(ScreenWidth/375.0) + 70 + 40
    
    /**
     数据类型 #1:用户,2:特质
     */
    fileprivate var data_type = 1
    
    
    /**
     首页展示人的 collectionView
     */
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.backgroundColor = Color.white
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_TraitOfOperatCell.self)
        
        
        
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_PeculiarityDetialSupplementView.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    

    //    MARK: - Filter
    fileprivate lazy var filter_btn:UIButton = {
        
        let control = UIButton.createFilterBtn()
        control.setTitleForAllStates("只看同城")
        control.addTarget(self, action: #selector(filter_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    fileprivate lazy var homeFilter:ST_PeculiarityAgeNeighborFilterController = {
        
       let vc = ST_PeculiarityAgeNeighborFilterController()
        return vc
    }()
    
    fileprivate lazy var home_filter_navigation_controller:UINavigationController = {
       
        let vc =  UINavigationController.create_hiding_bar_navigation_controller(rootViewController: homeFilter)
        
        vc.overCurrentContext = true
        
        return vc
    }()
    
    fileprivate var last_content_offset: CGFloat = 0
    
//    MARK:- Collection  Data Source
    fileprivate lazy var data_array = [ST_TraitOfOperatCellModel]()
    
//    MARK:- Play Operation
    fileprivate var current_play_index_path:IndexPath?
                                                        
    
    fileprivate func play(indexPath:IndexPath){
            
        pause_video()
        
        if TopmostViewController() != self{
            return
        }
        
        guard let cell = collectionView.cellForItem(at: indexPath) as? ST_ShowTraitCell , let dataItem = data_array[safe:indexPath.item] else{return}
        
        if dataItem.type != .video{
            
            return
        }
            
        cell.contentView.addSubview(playerView)
        
        let rect = cell.picutreframe_in_content_view()
         
        playerView.frame = rect
        
        
        
        let currModel = ST_PairsShareParticularModel.init(imageUrl: dataItem.imageUrl, videoUrl: dataItem.videoUrl, width: dataItem.width, height: dataItem.height)
        
        playerView.setUp(data_array: [currModel])
        
        current_play_index_path = indexPath
    }
    
    fileprivate func pause_video(){
        
        if playerView.frame.width == ScreenWidth{
            return
        }
        playerView.clear_data()
        
        if playerView.superview != nil {
            playerView.removeFromSuperview()
        }
        
        current_play_index_path = nil
    }
    
    
    fileprivate lazy var containerRect = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
    
    /**
     找出可以播放的indexPath
     */
    fileprivate func find_can_play_index_path(determineContinueBlock:((UICollectionViewCell)->(Bool)))->IndexPath?{
        
        var foundIndex:IndexPath?
        
        for item in collectionView.visibleCells {
            
            if determineContinueBlock(item){
                continue
            }
            
            if let cell = item as? ST_ShowTraitCell,cell.model.type == .video{
                
                if let playIdx = collectionView.indexPath(for: cell){

                 if let last = foundIndex,last.item < playIdx.item{
                     continue
                 }
                    
                let rectInScreen = collectionView.convert(cell.frame, to: nil)
                            
                let intersect = containerRect.intersection(rectInScreen)
                
                let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
                //               小于 70% 换下一个哈
                if percent < 0.8{
                    continue
                }
                
               foundIndex = playIdx
                }
            }
        }
        
        return foundIndex
    }
    
    /**
     确定播放下一个indexPath
     */
    fileprivate func determined_will_play_index_path()->IndexPath?{
        
        var foundIndex:IndexPath?
        
//        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let currCell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(currCell.frame, to: nil)
            
            let intersect = containerRect.intersection(rectInScreen)
            
            let percent = (intersect.width * intersect.height)/(rectInScreen.width * rectInScreen.height)
//               大于 50% 还是展示自己
            if percent > 0.5{
                return curr
            }else{
                foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                    return item == currCell
                })
            }
        }else{
            
                // 取出第一个 video cell 播放
            foundIndex = find_can_play_index_path(determineContinueBlock: { (item) -> (Bool) in
                return false
            })
        }
        
        print("cell视频---切换到另外一个Item:",foundIndex?.item ?? "🈚️")
        
        return foundIndex
    }
    
    
    
    
    
}



extension ST_PeculiarityDetailShowTraitController:CHTCollectionViewDelegateWaterfallLayout,UICollectionViewDataSource{
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return data_array[safe:indexPath.item]?.size ?? CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_TraitOfOperatCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
        cell.max_content_number_of_lines = 2
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        self.present_detail(indexPath: indexPath)
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForHeaderIn section: Int) -> CGFloat {
        
        return sectionheader_height
        
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_PeculiarityDetialSupplementView.self, for: indexPath)
        
        view.parent_peculiarity = self.parent_peculiarity
        
        if self.right_nav_btn.isHidden == false{
            view.settingClickButtonStatus()
        }
        
        return view
    }
    
//    MARK: Scroll Delegate
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let y = scrollView.contentOffset.y
        
        let offSet = sectionheader_height - y
        
        if offSet < 0{
            
            own_navigation_bar.alpha = 1
            
        }else if offSet >= own_navigation_bar_show_coefficient{
            
            own_navigation_bar.alpha = 0
        }else{
            own_navigation_bar.alpha = 1-offSet/own_navigation_bar_show_coefficient
        }
        
        //        判断当前正在播放的cell 在显示吗
        if let curr = current_play_index_path,let cell = collectionView.cellForItem(at: curr){
           
            let rectInScreen = collectionView.convert(cell.frame, to: nil)
            
            if containerRect.intersects(rectInScreen) == false{
                pause_video()
            }
        }
        
        
        
       if (self.last_content_offset > scrollView.contentOffset.y) {
           // move up
           
           UIView.animate(withDuration: 0.25) {
               self.filter_btn.alpha = 1
           }
           
           
       }
       else if (self.last_content_offset < scrollView.contentOffset.y) {
          // move down
           
           
           UIView.animate(withDuration: 0.25) {
               self.filter_btn.alpha = 0
           }
       }

       // update the new position acquired
       self.last_content_offset = scrollView.contentOffset.y
       
        
        
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
                scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
            scrollviewdidEndScroll(scrollView)
        
    }
    
//    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        guard let willPlayIdx = determined_will_play_index_path() else {
            
            pause_video()
            
            return
        }
        
        if let curr = current_play_index_path,curr.item == willPlayIdx.item{
            return
        }
        
        play(indexPath: willPlayIdx)
        
    }
    
}

//MARK: - Event
extension ST_PeculiarityDetailShowTraitController{
    
    @objc func filter_handle()  {
        
        
        homeFilter.refresh_closure = {[weak self] pm in
            
            self?.searchParam = pm
            self?.currentPage = 0
            self?.request_data()
            
            /*
            var str = "精准搜索"
            if let s = pm["is_same_city"] as? Int,s == 1{
                str = "只看同城"
            }
            
            
            self?.filter_btn.setTitleForAllStates(str)
            */
            
        }
        
        GlobalPresent(toController: home_filter_navigation_controller)
        
    }
    
}
//MARK: - Navigation Bar Event
extension ST_PeculiarityDetailShowTraitController{
    
    @objc func title_click(){
        
    }
    @objc func right_click(){
        
        
        let alert = ST_BTSheetActionController()
        
        var sheet_title = ""
        
        if parent_peculiarity.authJson["type"].intValue == 1{
//            已喜欢
            if parent_peculiarity.authJson["is_like"].boolValue{
              sheet_title = "不喜欢这个特质"
            }
//       喜欢特质
            else{
              sheet_title = "喜欢这个特质"
            }
        }
//            添加特质
        else if parent_peculiarity.authJson["type"].intValue == 2{
            sheet_title = "我要添加这个特质"
        }
        
        let attrString = NSMutableAttributedString(string: sheet_title)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        alert.addAction(ST_BTAlertAction.init(title: attrString, handler: {[weak self] action in
                
            guard let strongSelf = self else{
                return
            }
            switch sheet_title{
                
                case "不喜欢这个特质":
                    JVrequest(PH.unlikePeculiarityApi,parameters: ["feature_id":strongSelf.parent_peculiarity.id],success: { (json) in
                        self?.currentPage = 0
                        self?.request_data()
                        
                        NotificationCenter.default.post(name: Notification.Name.like_peculiarity, object: nil)
                        
                    }) { (code, err) in
                        
                        ToastHud(text: err, view: strongSelf.view)
                    }
                    break
                case "喜欢这个特质":
                    
                    JVrequest(PH.likePeculiarityApi,parameters: ["feature_id":strongSelf.parent_peculiarity.id],success: { (json) in
                        self?.currentPage = 0
                        self?.request_data()
                        
                    }) { (code, err) in
                        
                        ToastHud(text: err, view: strongSelf.view)
                    }
                    break
                default:
//                    添加特质
                    willPushPeculiarity = strongSelf.parent_peculiarity
                    
                    push_peculiarity(navigationController: self?.navigationController, operationController: ST_PushPeculiaritySelectMediaController())
                    
                    break
            }
            
        }))
        
        alert.show()
        
        
    }
    @objc func left_click(){
        
        self.goback_previous_controller()
    }
}

//MARK: - 跳转详情
extension ST_PeculiarityDetailShowTraitController{
    
    
    func present_detail(indexPath:IndexPath) {
        
        
        guard let currCell = collectionView.cellForItem(at: indexPath),let objCell = currCell as? ST_PecGroupshareViewRectProtocol else{
                return
            }
            
            let model = data_array[indexPath.row]

            //      当前正在播放 并且不是当前点击这个
            if current_play_index_path != indexPath{
                
                pause_video()
    //            1视频 2 图片
                if model.type == .video{

                    let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, videoUrl: model.videoUrl, width: model.width, height: model.height)
                    
                    playerView.setUp(data_array: [currModel])
                }else{
                    
                    let currModel = ST_PairsShareParticularModel.init(imageUrl: model.imageUrl, width: model.width, height: model.height)
                    
                    playerView.setUp(data_array: [currModel])
                    
                }
                
            }
            
            transition.operationView = self.playerView
            
            let rectInScreen = currCell.convert(objCell.picutreframe_in_content_view(), to: nil)
            
            playerView.present_start_rect = rectInScreen
            playerView.present_start_idx = indexPath
            playerView.fromeController = self
         
            let item = model
        
        ST_InteractiveST_PeculiarityGroupViewController.present_interactive_peculiarity_group_controller(accid: item.accid, groupId: item.group_id.string, peculiarity_id: item.feature_id.string, remark: item.sign, firstPhotoSize: CGSize.init(width: item.width, height: item.height), transition: transition, presentRootController: self)
        
    }
    
    
    
}


extension ST_PeculiarityDetailShowTraitController:ST_PairsTransitionProtocol{
    
    
    func present_start_cell()->UICollectionViewCell?{
        
        guard let idx = playerView.present_start_idx  else {
            return nil
        }
        
        return self.collectionView.cellForItem(at: idx)
        
    }
    
}



//MARK: - Today Style
class ST_TodayTraitController: ST_PeculiarityDetailShowTraitController {
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        left_nav_btn.isHidden = true
        
        right_nav_btn.setImageForAllStates(ST_ImageUtils.imageName("特质_icon_关闭")!)
        
        
        collectionView.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_TodayTraitHeaderReusableView.self)
    }
    
    override func right_click() {
        
        goback_previous_controller()
        
    }
    
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForHeaderIn section: Int) -> CGFloat {
        return 490 + 20
    }
    
//    @objc override func collectionView(_ collectionView: UICollectionView!, layout collectionViewLayout: UICollectionViewLayout!, heightForHeaderInSection section: Int) -> CGFloat {
//
//        return 490 + 20
//
//    }
    
    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_TodayTraitHeaderReusableView.self, for: indexPath)
        
        view.parent_peculiarity = self.parent_peculiarity
        
        return view
    }
    
}
